import re
import string
from channels.channels import Channel

class Lines2LinesNLSm(Channel):
    """
    Convert lines to lines by regex. 
    number letter symbol_map
    """
    required = ['lines']
    send = ['lines']

    def char_map(self):
        """符号映射"""
        # regex_flags = r'/^[\u4e00-\u9fa5_a-zA-Z0-9\s\·\~\！\@\#\￥\%\……\&\*\（\）\——\-\+\=\【\】\{\}\、\|\；\‘\’\：\“\”\《\》\？\，\。\、\`\~\!\#\$\%\^\&\*\(\)\_\[\]{\}\\\|\;\'\'\:\"\"\,\.\/\<\>\?]+$/'
        # seg_flags = r'/^[u4e00-u9fa5_a-zA-Z0-9s·~！@#￥%……&*（）——-+=【】{}、|；‘’：“”《》？，。、`~!#$%^&*()_[]{}|;\'\':"",./<>?]+$'
        # seg_flags = r'/^[u4e00-u9fa5_a-zA-Z0-9s·~！@#￥%……&*（）——-+=【】{}、|；‘’：“”《》？，。、`~!#$%^&*()_[]{}|;\'\':"",./<>?]+$'
        
        map_dict = {
            '，': r'\^\[\]\·\~\@\￥\%\…\&\*\（\）\—\-\+\=\【\】\{\}\、\|\；\‘\’\：\“\”\《\》\，\、\`\~\ \#\$\%\^\&\(\)\_\{\}\|\; \\\'\:\"\,\/\<\>\]\$',
            '。': r'\！\。\!\.',
            '？': r'\？\?',
        }
        return map_dict
    
    @staticmethod
    def execute(args={}, meta={}, lines:list=[], **kwargs):
        # symbol map
        map_dict = Lines2LinesNLSm().char_map()

        # replace
        for index, line in enumerate(lines):
            for key, reg in map_dict.items():
                line, n = re.subn(r'['+ reg +']', key, line)
            segL_res = re.split(r'['+''.join(map_dict.keys())+']', line)

            lines_news = []
            line_limit = args.get('para_limit', [0, 20000])
            for res in segL_res:
                line_len = len(res)
                if line_len >= line_limit[0] and line_len <= line_limit[1]:
                    lines_news.append(res)

            # bar show
            args.bar_show(index, len(lines))

        return {
            'args': args,
            'meta': meta,
            'lines': lines_news
        }


if __name__ == "__main__":
    # seg_flags = r'/^[\u4e00-\u9fa5_a-zA-Z0-9\s\·\~\！\@\#\￥\%\……\&\*\（\）\——\-\+\=\【\】\{\}\、\|\；\‘\’\：\“\”\《\》\？\，\。\、\`\~\!\#\$\%\^\&\*\(\)\_\[\]{\}\\\|\;\'\'\:\"\"\,\.\/\<\>\?]+$/'
    # print(seg_flags.replace('\\', ''))

    # Test the expression of regex
    regex = r'[\^\[\]\·\~\@\￥\%\…\&\*\（\）\—\-\+\=\【\】\{\}\、\|\；\‘\’\：\“\”\《\》\，\、\`\~\ \#\$\%\^\&\(\)\_\{\}\|\; \\\'\:\"\,\/\<\>\]\$]'
    content = '!真不错啊，你说呢。还行吧， 你说呢#，还可以。!'
    content, _ = re.subn(regex, '', content)
    print(content)

